package cn.edu.zstu.qingzhu.qingzhushop.security;

import cn.edu.zstu.qingzhu.qingzhushop.entity.Resource;
import cn.edu.zstu.qingzhu.qingzhushop.entity.Role;
import cn.edu.zstu.qingzhu.qingzhushop.service.IResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @Author ShenTuZhiGang
 * @Version 1.0.0
 * @Date 2020-03-07 21:57
 */
@Component
public class CustomFilterInvocationSecurityMetadataSource
        implements FilterInvocationSecurityMetadataSource {
    private static Map<String, Collection<ConfigAttribute>> resourceMap = null;
    AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Autowired
    private IResourceService iResourceService;

    private void loadResourcePermission() {
        List<Resource> resources = iResourceService.getAllResource();
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        String ruquestUrl = ((FilterInvocation) o).getRequestUrl();
        List<Resource> resources = iResourceService.getAllResource();
        for (Resource resource : resources) {
            if (antPathMatcher.match(resource.getPattern(), ruquestUrl)
                    && resource.getRoles().size() > 0) {

                List<Role> roles = resource.getRoles();
                String[] roleArr = new String[roles.size()];
                for (int i = 0; i < roleArr.length; i++) {
                    roleArr[i] = roles.get(i).getName();
                }
                return SecurityConfig.createList(roleArr);
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
